<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="400px" :before-close="handleClose">
    <el-button @click="handleClickCreate" class="mb-2"> 新建 </el-button>
    <Table
      :columns="columns"
      :data="queryData"
      @row-dblclick="handleTableDblclick"
      class="lable-manage"
    >
      <template #sort>
        <div class="flex items-center">
          <Icon
            icon="material-symbols:drag-pan"
            data-inline="false"
            class="drag-label cursor-grab"
            @mouseenter="rowDrop()"
            style="margin-left: 10px"
          />
        </div>
      </template>
      <template #color="{ row }">
        <div :style="{ 'background-color': row.color, height: '2em' }" class="ml-1 mr-1"></div>
      </template>
      <template #menu="{ row }">
        <context-menu-item label="编辑" @click="handleMenuUpdate(row)" />
        <context-menu-item label="删除" @click="handleMenuDelete(row)" />
      </template>
    </Table>
  </Dialog>
  <MailLabelEdit ref="labelEditRef" @success="getList" />
</template>
<script setup name="MailLabelManage" lang="ts">
import MailLabelEdit from '@/views/mailbox/mail/MailLabelEdit.vue'
import * as MailApi from '@/api/mailbox/mail'
import Sortable from 'sortablejs'
const message = useMessage() // 消息弹窗
const labelEditRef = ref()
const dialogTitle = ref('标签管理')
const dialogVisible = ref(false)
const queryData = ref()
const ownerUserId = ref(0)
const columns = [
  {
    label: '排序',
    prop: 'sort',
    width: '40px',
    slot: 'sort'
  },
  {
    label: '标签名称',
    prop: 'name'
  },
  {
    label: '颜色',
    prop: 'color',
    slot: 'color'
  }
]
/** 初始化 */
const open = (userId) => {
  ownerUserId.value = userId
  getList()
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 新建按钮操作 */
const handleClickCreate = () => {
  labelEditRef.value.open('create', '', ownerUserId.value)
}

/** 编辑按钮操作 */
const handleMenuUpdate = (row) => {
  labelEditRef.value.open('update', row.id, ownerUserId.value)
}

/** 处理响应事件  */
const getList = async () => {
  queryData.value = await MailApi.listLabel(ownerUserId.value)
}

/** 处理table行双击事件 */
const handleTableDblclick = (row) => {
  labelEditRef.value.open('update', row.id)
}

/** 处理右击事件 删除 */
const handleMenuDelete = async (row) => {
  await message.confirm('确认要删除此标签吗？')
  await MailApi.deleteLabel(row.id)
  getList()
}

const emit = defineEmits(['close'])

const rowDrop = () => {
  nextTick(() => {
    const wrapper: HTMLElement | null = document.querySelector(
      '.lable-manage .el-table__body-wrapper tbody'
    )
    Sortable.create(wrapper, {
      animation: 300,
      handle: '.drag-label',
      onEnd: async ({ newIndex, oldIndex }) => {
        const currentRow = queryData.value.splice(oldIndex, 1)[0]
        queryData.value.splice(newIndex, 0, currentRow)
        await MailApi.labelSort({
          id: currentRow.id,
          oldIndex: oldIndex,
          newIndex: newIndex,
          ownerId: ownerUserId.value
        })
      }
    })
  })
}

const handleClose = () => {
  dialogVisible.value = false
  emit('close')
}
</script>
